import classNames from 'classnames'
import Taro, { Component, showLoading } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { DNavBar, DImagesupload, DSelectColor, DAtInpute, DSelectMap, DButtonModal } from '@/components'
import { AtForm, AtButton, AtSwitch, AtActionSheet, AtInput } from 'taro-ui'
import http from '@/api'
import common from '@/common'
import sdk from '@/common/sdk'
import './carform.scss'
const countMinPri = common.countMinPri
export default class CarformBox extends Component {

  constructor(props) {
    super(props)
    this.state = {
      title: '发布车源',
      isOpenedColor: false,
      status: '2',
      seletOne: {
        defNoop: () => {
          this.state.seletOne.isOpened = false
          this.setState({
            seletOne: { ...this.state.seletOne },
          })
        }
      }, // 单选对象
      carform: {},
      // 颜色key值
      colorKey: "",
      selectColor: "",
      colorCount: 2,
      type: "",
      disabled: true,
      tips1: '请选择车辆类型'
    }
  }


  componentWillMount() {
    let { status = '2', id = '', type = '' } = this.$router.params
    let { title } = this.state
    if (status === '1') {
      title = '发布寻车'
    }
    if (id) {
      this.httpGetCarDetail({ id })
    }
    sessionStorage.removeItem('brandList')
    this.setState({
      status,
      title,
      type
    })
  }

  componentDidShow() {
    this.getBrandInfo()
    sdk.setTitleInfo(this.state.title)
  }

  getFilterPlace(first, second) {
    let _itemPlace = ['北京市', '天津市', '上海市', '重庆市']
    _itemPlace.map(item => {
      if (item === first) {
        second = item
      }
    })
    return second
  }


  getBrandInfo() {
    let _brandList = sessionStorage.getItem('brandList')

    if (!_brandList) {
      return
    }
    let { carBrand = '',
      carBrandId = '',
      carBrandLogo = '',
      carModel = '',
      carSourceType = '',
      carGuiPrice = 0,
      carModelId = '',
      carSeries = '',
      carSeriesId = '',
      waiguanyanse = '',
      neigaunyanse = '',
    } = JSON.parse(_brandList)
    // carGuiPrice = Number(carGuiPrice/10000).toFixed(2)
    // let arr = carModel.split(' ')
    let _obj = {
      carDataBrand: carBrand,
      carDataBrandId: carBrandId,
      carDataBrandLogo: carBrandLogo,
      carDataModel: carModel,
      carSourceType: carSourceType,
      carGuiPrice: carGuiPrice,
      carDataModelId: carModelId,
      carDataSeries: carSeries,
      carDataSeriesId: carSeriesId,
    }
    let { carform } = this.state

    carform = Object.assign(carform, _obj)
    this.setState({
      carform,
      neigaunyanse,
      waiguanyanse

    }, () => {
      sessionStorage.removeItem('brandList')
    })
  }

  httpGetCarDetail(id) {
    let { status } = this.$router.params
    let _http
    if (+status === 1) {
      // 车源详情
      _http = http.getCarSourceDetail(id)
    } else {
      // 寻车详情
      _http = http.getCarSearchDetail(id)
    }
    let { carform } = this.state
    _http.then(res => {
      carform = Object.assign({}, res)
      carform.carRemark = ''
      this.setState({
        carform
      })
    })
  }

  onSubmitHandle() {
    let { carform, status, title, disabled, tips1 } = this.state
    let _obj = {
      carBussType: status,
      carEdition: "",
      carFrameNo: "",
      carModel: "",
      carSourceSellDis: "",
      carSourceValidityEnd: "",
      carStyle: "",
      carType: "",
      carTypeCode: "",
      fileList: []
    }
    function getTitle(status) {
      return {
        $1: '已发布寻车',
        $2: '已发布车源'
      }[`$${status}`]
    }
    function urlInfo(status) {
      return {
        $1: '/pages/index/index',
        $2: '/pages/usercar/usercar'
      }[`$${status}`]
    }
    if (disabled) {
      return Taro.showToast({
        icon: "none",
        title: tips1
      })
    }
    if (carform['carGuiPrice'] > 0) {
      if ((0.5 * Number(carform['carGuiPrice'])) > Number(carform['carOfferPrice']) || Number(carform['carOfferPrice']) > (2 * Number(carform['carGuiPrice']))) {
        return Taro.showToast({
          title: `请输入${status === '2' ? '车辆报价' : '期望报价'}是车辆指导价的0.5或者2倍之间`,
          icon: 'none'
        })
      }
    }

    let car = Object.assign({}, _obj, carform)
    http.commitReleaseCar(car)
      .then(res => {
        Taro.showToast({
          title: getTitle(status),
          duration: 800,
          mask: true
        }).then(() => {
          setTimeout(() => {
            Taro.redirectTo({
              url: urlInfo(status)
            })
          }, 1000)
        })
      })
      .catch(() => {
        Taro.showToast({
          title: "网络异常！",
          icon: "none"
        })
      })
  }


  onRightHanlde(key) {
    let { waiguanyanse, neigaunyanse } = this.state
    let isOut = key === 'carOutColor'
    this.setState({
      isOpenedColor: true,
      colorKey: key,
      listColr: common.getSplitColor(isOut ? waiguanyanse : neigaunyanse),
      colorCount: isOut ? 0 : 2,
      selectColor: this.state.carform[key]
    })
  }

  onCancelHandle() {
    this.setState({
      isOpenedColor: false
    })
  }

  onSubmitColor(value) {
    let { colorKey } = this.state
    let color = []
    value.map(item => {
      color.push(item.color)
    })
    this.bindCarform(colorKey, color.join('/'))
    this.setState({
      isOpenedColor: false
    })
  }

  onHandleSelect() {
    Taro.navigateTo({
      url: "/pages/choosebrand/choosebrand"
    })
  }

  initSelectOne = ({ title, bind }, sList) => {
    return new Promise((res, rej) => {
      this.setState({
        seletOne: {
          ...this.state.seletOne,
          isOpened: true,
          title,
          sList: sList.filter(item => (item.status = this.state.carform[bind] === item.text, true)), // 反显高亮值
          selectListItem: (item) => {
            item.status = !item.status
            if (item.status) {
              this.state.seletOne.value = item
              res.call(this, item)
            }
            this.state.seletOne.isOpened = false
            this.setState({
              seletOne: { ...this.state.seletOne },
            })
          }
        }
      })
    })
  }

  bindCarform = (key, value) => {
    if (key) {
      if (key === 'carOfferPrice') {
        let Digit = common.getDigit(value, this.state.carform.carOfferPrice)
        // debugger
        this.setState({
          carform: Object.assign(this.state.carform, { [key]: Digit }),
        }, () => {
          this.getCarStatus()
        })
      } else {
        this.setState({
          carform: Object.assign(this.state.carform, { [key]: value }),
        }, () => {
          this.getCarStatus()
        })
      }
    }

  }

  getCarStatus() {
    let { carform, status } = this.state
    let _statusForm = false, _item = ''
    if (status === '1') {
      let _carformfirst = ['carDataModel', 'carGuiPrice', 'carOutColor',
        'carEmissionStd', 'carSourceAddr', 'carSearchType', 'carSearchValidity']
      let objtext = {
        carDataModel: '请选择车辆类型',
        carOutColor: '请选择车辆外观颜色',
        carEmissionStd: '请选择车辆排放标准',
        carSourceAddr: '请选择车辆上牌地点',
        carSearchType: '请选择寻车状态',
        carSearchValidity: '请选择寻车有效期'
      }
      for (let i = 0, j = _carformfirst.length; i < j; i++) {
        if (!carform[_carformfirst[i]]) {
          _statusForm = true
          _item = objtext[_carformfirst[i]]
          break
        }
      }

      // _carformfirst.map(item => {
      //   if (!carform[item]) {
      //     _statusForm = true
      //   }
      // })

    } else if (status === '2') {
      let _carformfirst = ['carDataModel', 'carGuiPrice', 'carOfferPrice', 'carOutColor',
        'carEmissionStd', 'carSourceValidity', 'carSourceAddr']

      let objtext = {
        carDataModel: '请选择车辆类型',
        carOfferPrice: '请输入您的报价',
        carOutColor: '请选择车辆外观颜色',
        carEmissionStd: '请选择车辆排放标准',
        carSourceAddr: '请选择车源所在地',
        carSourceValidity: '请选择车源有效期'
      }
      for (let i = 0, j = _carformfirst.length; i < j; i++) {
        if (!carform[_carformfirst[i]]) {
          _statusForm = true
          _item = objtext[_carformfirst[i]]
          break
        }
      }
      // _carformfirst.map(item => {
      //   if (!carform[item]) {
      //     _statusForm = true
      //   }
      // })
    }

    this.setState({
      disabled: _statusForm,
      tips1: _item
    })
  }

  selectCarPop = (props) => {
    this.initSelectOne(props, [
      { text: '国五' },
      { text: '国六' },
      { text: '纯电动' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarDate = (props) => {
    this.initSelectOne(props, [
      { text: '3' },
      { text: '7' },
      { text: '15' },
      { text: '30' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectHandInfo = (props) => {
    this.initSelectOne(props, [
      { text: '手续齐全' },
      { text: '手续办理中' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarSource = (props) => {
    this.initSelectOne(props, [
      { text: '自店' },
      { text: '资源' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarGoodDate = props => {
    this.initSelectOne(props, [
      { text: '现货' },
      { text: '期货' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarStatus = props => {
    this.initSelectOne(props, [
      { text: '客户寻车，寻求报价' },
      { text: '订金在手，价好即接' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  render() {
    const {
      title,
      isOpenedColor,
      carform,
      status,
      seletOne,
      selectColor,
      listColr,
      colorCount
    } = this.state
    const _bindCarform = function (value) {
      this.bindCarform(arguments[arguments.length - 1].bind, value)
    }
    const _swichBindCarform = function (key, value) {
      this.bindCarform(key, +value)
    }
    const _selectMap = function (key, value) {
      let { first = '', secode = '' } = value
      let region = first + secode
      if (status === '1') {
        this.bindCarform("carTransAddr", this.getFilterPlace(first, secode))
        this.bindCarform('carTransAddrDetail', first === this.getFilterPlace(first, secode) ? first : region)
        this.bindCarform('carTransDis', first)
      }
      this.bindCarform(key, region)
    }
    const _imageList = function (key, value) {
      let _value = []
      value.map(item => {
        if (item.url) {
          _value.push({
            id: item.id,
            type: item.uploadType,
            cfUrl: item.url
          })
        }
      })
      this.bindCarform(key, _value)
    }

    return (
      <View className='b_carform'>
        <DNavBar title={title}></DNavBar>
        <View className='b_carform__box'>
          <View className='b_carform__form'>
            <AtForm>
              <View className='b_carform__form__item'>
                <Text className='b_carform__form_title'>车辆信息</Text>
                <DAtInpute value={carform.carDataModel} bind='carDataModel' onChange={_bindCarform.bind(this)} title='车辆信息' icon='chevron-right' require={true} placeholder='请选择车辆类型' onRightHanlde={this.onHandleSelect.bind(this)}></DAtInpute>
                <DAtInpute value={carform.carSourceType} bind='carSourceType' onChange={_bindCarform.bind(this)} title='车辆类型' icon='none'></DAtInpute>
                <DAtInpute value={carform.carGuiPrice == 0 ? '面议' : carform.carGuiPrice} bind='carGuiPrice' type="number" title='车辆指导价' icon='none'>{ carform.carGuiPrice > 0 && '万' }</DAtInpute>
                {
                  status === '2' && <DAtInpute value={carform.carOfferPrice} bind='carOfferPrice' type="number" onChange={_bindCarform.bind(this)} title='车辆报价' require={true} placeholder='请输入您的报价'> 万</DAtInpute>
                }
                {
                  status === '2' && <DAtInpute editable={false} type="number" title='差额（与指导价相比）' >{countMinPri(carform.carOfferPrice || 0, carform.carGuiPrice || 0)}万</DAtInpute>
                }
                <DAtInpute value={carform.carOutColor} bind='carOutColor' onChange={_bindCarform.bind(this)} title='外观颜色' require={true} icon='chevron-right' placeholder='请选择车辆外观颜色' onRightHanlde={this.onRightHanlde.bind(this, 'carOutColor')}></DAtInpute>
                <DAtInpute value={carform.carInColor} bind='carInColor' onChange={_bindCarform.bind(this)} title='内饰颜色' icon='chevron-right' placeholder='请选择车辆内饰颜色' onRightHanlde={this.onRightHanlde.bind(this, 'carInColor')}></DAtInpute>
                <DAtInpute value={carform.carEmissionStd} bind='carEmissionStd' onChange={_bindCarform.bind(this)} require={true} title='排放标准' icon='chevron-right' placeholder='请选择车辆排放标准' onRightHanlde={this.selectCarPop}></DAtInpute>
              </View>
              {
                status === '1' && <View className='b_carform__form__item'>
                  <Text className='b_carform__form_title'>交易信息</Text>
                  <DAtInpute value={carform.carOfferPrice} bind='carOfferPrice' onChange={_bindCarform.bind(this)} title='期望报价' type='number' placeholder='请输入期望报价'>万</DAtInpute>
                  {/* <DAtInpute editable={false} type="number" title='' >{countMinPri(carform.carOfferPrice || 0, carform.carGuiPrice || 0)}万</DAtInpute> */}
                  <View className="form-item">
                    <View className="form-item-label">差额（与指导价相比）</View>
                    <View className="form-item-value">{countMinPri(carform.carOfferPrice || 0, carform.carGuiPrice || 0)}万</View>
                  </View>

                  <DSelectMap value={carform.carSourceAddr} bind='carSourceAddr' require={true} onChangeHandle={_selectMap.bind(this, 'carSourceAddr')} title='上牌地点' icon='chevron-right' placeholder='请选择车辆上牌地点'></DSelectMap>
                  <DAtInpute value={carform.carSearchType} bind='carSearchType' require={true} onChange={_bindCarform.bind(this)} title='寻车状态' icon='chevron-right' placeholder='请选择寻车状态' onRightHanlde={this.selectCarStatus}></DAtInpute>
                  <DAtInpute value={carform.carSearchValidity} bind='carSearchValidity' require={true} onChange={_bindCarform.bind(this)} title='寻车有效期' icon='chevron-right' placeholder='请选择寻车有效期' onRightHanlde={this.selectCarDate}>{carform.carSearchValidity ? '天' : ''}</DAtInpute>
                </View>
              }
              {
                status === '2' && <View className='b_carform__form__item'>
                  <Text className='b_carform__form_title'>交易信息</Text>
                  <DAtInpute value={!!carform.carSourceValidity ? carform.carSourceValidity + '天' : carform.carSourceValidity} bind='carSourceValidity' require={true} onChange={_bindCarform.bind(this)} title='车源有效期' icon='chevron-right' placeholder='请选择车辆有效期' onRightHanlde={this.selectCarDate}></DAtInpute>
                  <DAtInpute value={carform.carSourceProc} bind='carSourceProc' onChange={_bindCarform.bind(this)} title='手续' icon='chevron-right' placeholder='请选择车辆手续办理情况' onRightHanlde={this.selectHandInfo}></DAtInpute>
                  <DAtInpute value={carform.carSourceAtt} bind='carSourceAtt' onChange={_bindCarform.bind(this)} title='车辆性质' icon='chevron-right' placeholder='请选择车源性质' onRightHanlde={this.selectCarSource}></DAtInpute>
                </View>
              }
              {
                status === '1' && <View className='b_carform__form__item'>
                  <AtSwitch color="rgb(255,190,0)" checked={carform.carIsHideContact} bind='carIsHideContact' onChange={_swichBindCarform.bind(this, 'carIsHideContact')} title='是否隐藏联系方式'></AtSwitch>
                </View>
              }
              <View className='b_carform__form__item'>
                {
                  status === '2' && <View className='b_carform__form__item__other'>
                    <Text className='b_carform__form_title'>其他信息</Text>
                    <DSelectMap value={carform.carSourceAddr} require bind='carSourceAddr' onChangeHandle={_selectMap.bind(this, 'carSourceAddr')} title='车源地点' icon='chevron-right' placeholder='请选择车源所在地'></DSelectMap>
                    <AtSwitch color="rgb(255,190,0)" checked={carform.carIsPurchaseInsurance} bind='carIsPurchaseInsurance' onChange={_swichBindCarform.bind(this, 'carIsPurchaseInsurance')} title='是否已购买店内保险'></AtSwitch>
                    <AtSwitch color="rgb(255,190,0)" checked={carform.carIsMortgage} bind='carIsMortgage' onChange={_swichBindCarform.bind(this, 'carIsMortgage')} title='是否可以店内按揭'></AtSwitch>
                    <DAtInpute value={carform.carSourcePt} bind='carSourcePt' onChange={_bindCarform.bind(this)} title='货期' icon='chevron-right' placeholder='请选择该车源货期' onRightHanlde={this.selectCarGoodDate}></DAtInpute>
                    <View className='b_carform__images'>
                      <Text className="b_carform__images_title">车源照片(最多可上传四张)</Text>
                      <DImagesupload value={carform.fileList} bind='fileList' onChangeImages={_imageList.bind(this, 'fileList')} count={4}></DImagesupload>
                    </View>
                  </View>
                }
                <DAtInpute value={carform.carRemark} bind='carRemark' maxLength={500} onChange={_bindCarform.bind(this)} title='备注' placeholder='可输入相关备注信息'></DAtInpute>
              </View>
            </AtForm>
          </View>
          <View className='b_carform__footer'>
            <AtButton className='item_btn' onClick={this.onSubmitHandle.bind(this)}>{title}</AtButton>
            {/* <DButtonModal text={title} primanyBtn></DButtonModal> */}
          </View>
        </View>

        <DSelectColor list={listColr} count={colorCount} value={selectColor} isOpened={isOpenedColor} onCancelHandle={this.onCancelHandle.bind(this)} onSubmitHandle={this.onSubmitColor.bind(this)}></DSelectColor>
        <View>
          <AtActionSheet className="at-select-one" isOpened={seletOne.isOpened} onClose={seletOne.onClose || seletOne.defNoop}>
            <View className='at-select-one__title'>
              <View className='at-select-one__title_cancel' onClick={seletOne.cancel || seletOne.defNoop}>{seletOne.cancelText || '取消'}</View>
              <View className='at-select-one__title_item'>{seletOne.title}</View>
              <View className='at-select-one__title_submit' onClick={seletOne.commit || seletOne.defNoop}>{seletOne.commitText || '提交'}</View>
            </View>
            <View className='at-select-one__type'>
              {
                seletOne.sList && seletOne.sList.map((item, i) => {
                  return <View onClick={seletOne.selectListItem.bind(this, item)} className={classNames('at-select-one__type_item', item.status ? 'at-select-one__active' : '')} key={i}>{item.text}</View>
                })
              }
            </View>
          </AtActionSheet>
        </View>
      </View>
    )
  }
}
